package com.cgy.utils.base.map.stream;

import com.cgy.utils.base.json.JsonHelper;
import com.cgy.utils.base.map.MapHelper;

import java.util.List;
import java.util.Map;

/**
 * 流式操作
 * @author CHTK
 */
public class MapStreamBuilder<K, V> {

    private Map<K, V> t;

    private int size;
    private boolean isNull;

    public MapStreamBuilder(Map<K, V> map) {
        this.t = map;
    }

    /**
     * 初始化
     * @param map
     * @return
     */
    public MapStreamBuilder<K, V> map(Map<K, V> map) {
        this.t = MapHelper.newMap(map);
        this.size = MapHelper.mapSize(map);
        return this;
    }

    /**
     * 添加值
     * @param k
     * @param v
     * @return
     */
    public MapStreamBuilder<K, V> put(final K k, final V v) {
        MapHelper.put(this.t, k, v);
        return this;
    }

    /**
     * 序列化空值
     * @return
     */
    public MapStreamBuilder<K, V> serializeNulls() {
        this.isNull = true;
        return this;
    }

    /**
     * 遍历
     * @param foreachHandler
     * @return
     */
    public MapStreamBuilder<K, V> foreach(final ForeachHandler<K, V> foreachHandler) {
        if (null != foreachHandler) {
            this.t = MapHelper.iterator(this.t, new MapHelper.IteratorHandler<K, V>() {
                @Override
                public void next(K k, V v) {
                    if(isNull) {
                        foreachHandler.next(k, v);
                    } else {
                        if(null != v) {
                            foreachHandler.next(k, v);
                        }
                    }
                }
            });
        }
        return this;
    }

    /**
     * 获取 list
     * @return
     */
    public List<K> toKeyList() {
        return MapHelper.keyList(this.t);
    }
    /**
     * 获取 list
     * @return
     */
    public List<V> toValueList() {
        return MapHelper.valueList(this.t);
    }
    /**
     * 获取Map
     * @return
     */
    public Map<K, V> toMap() {
        return this.t;
    }

    /**
     * 获取 json
     * @return
     */
    public String toJson() {
        return JsonHelper.toJson(this.t);
    }
    /**
     * 
     * @return
     */
    public int size() {
    	return this.size;
    }

    /**
     *
     */
    public static interface ForeachHandler<K, V> {
        /**
         * 遍历
         * @param k
         * @param v
         * @return
         */
        public V next(K k, V v);
    }
}
